<template>
  <div class="contract-apply-container">
    <el-card class="form-card" shadow="never">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>{{ isEditMode ? '合同变更申请' : '新合同申请' }}</h1>
        <p class="subtitle">请填写完整的合同信息，带<span class="required">*</span>为必填项</p>
      </div>

      <!-- 主表单区域 -->
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="formRules" 
        label-width="150px" 
        label-position="right"
        class="contract-form"
      >
        <!-- 基本信息行 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <!-- 合同编号 -->
            <el-form-item label="合同编号：" prop="contractId">
              <el-input v-model="form.contractId" disabled />
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="合同名称：" prop="title">
              <el-input 
                v-model="form.title" 
                placeholder="请输入合同名称" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

     

        <!-- 申请人和企业信息行 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="申请人：" prop="applicant">
              <el-input 
                v-model="form.applicant" 
                placeholder="请输入申请人姓名" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称：" prop="partyBCompany">
              <el-input 
                v-model="form.partyBCompany" 
                placeholder="请输入企业名称" 
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日期信息行 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="生效日期：" prop="contractStartDate">
              <el-date-picker
                v-model="form.contractStartDate"
                type="date"
                placeholder="选择生效日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期日期：" prop="contractEndDate">
              <el-date-picker
                v-model="form.contractEndDate"
                type="date"
                placeholder="选择到期日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址和变更原因行 -->
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="企业地址：" prop="partyBAddress">
              <el-input 
                v-model="form.partyBAddress" 
                placeholder="请输入企业地址" 
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isEditMode">
            <el-form-item label="变更原因：" prop="changeReason" required>
              <el-input
                v-model="form.changeReason"
                type="textarea"
                :rows="2"
                placeholder="请输入合同变更原因"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 附件上传区域 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同附件：" prop="attachments" required>
              <el-upload
                action="#"
                multiple
                :limit="5"
                :file-list="attachments"
                :auto-upload="false"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
                drag
                :on-exceed="handleExceed"
                class="upload-area"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  拖拽文件到此处或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传PDF、Word、Excel、图片等格式，单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 表单操作按钮 -->
        <el-row>
          <el-col :span="24" class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="submitting">
              {{ isEditMode ? '提交变更' : '提交申请' }}
            </el-button>
            <el-button @click="resetForm">重置表单</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 提交成功对话框 -->
    <el-dialog
      v-model="successDialogVisible"
      title="提交成功"
      width="500px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="success-message">
        <el-icon color="#67C23A" :size="60"><CircleCheck /></el-icon>
        <h3>{{ isEditMode ? '合同变更申请已提交' : '新合同申请已提交' }}</h3>
        <p>您的申请已成功提交，请等待审批</p>
        <p>合同编号: {{ form.contractId }}</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSuccessConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Plus, UploadFilled, CircleCheck } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useContractStore } from '@/stores/contractStore'
import { useContractHistoryStore } from '@/stores/contractHistory'
import axios from 'axios'
const router = useRouter()
const route = useRoute()
const contractStore = useContractStore()
const contractHistory = useContractHistoryStore()
// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})
// 表单引用
const formRef = ref(null)

// 表单数据
const form = ref({
  contractId: '',
  title: '',
  applicant: '',
  contractStartDate: '',
  partyBCompany: '',
  partyBAddress: '默认乙方地址',
  contractEndDate: '',
  changeReason: '',
  status: '待审批',
  attachments: []
})

// 附件列表
const attachments = ref([])

// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  applicant: [{ required: true, message: '请输入申请人', trigger: 'blur' }],
  contractStartDate: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  contractEndDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
  partyBCompany: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  partyBAddress: [{ required: true, message: '请输入企业地址', trigger: 'blur' }],
  changeReason: [{ 
    required: false,
    validator: (rule, value, callback) => {
      if (isEditMode.value && !value) {
        callback(new Error('变更合同时必须填写变更原因'))
      } else {
        callback()
      }
    },
    trigger: 'blur' 
  }],
    attachments:[{
    required:true,
    validator:(rule,value,callback)=>{
      if(!issueForm.value.attachments || issueForm.value.length===0){
        callback(new Error('请上传合同附件'))
      }else{
        callback()
      }
    },
    trigger:'change'
  }]
}

// 是否编辑模式
const isEditMode = computed(() => {
  return route.params.id !== undefined || route.query.editMode === 'true'
})

// 提交状态
const submitting = ref(false)
const successDialogVisible = ref(false)

// 生成合同ID
const generateContractId = () => {
  return 'CT' + Date.now().toString().slice(-8)
}

// 重置表单
const resetForm = () => {
  form.value = {
    contractId: generateContractId(),
    title: '',
    applicant: '',
    contractStartDate: '',
    partyBCompany: '',
    partyBAddress: '默认乙方地址',
    contractEndDate: '',
    changeReason: '',
    status: '待审批',
    attachments: []
  }
  attachments.value = []
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch(status) {
    case '已通过': return 'success'
    case '待审批': return 'warning'
    case '已拒绝': return 'danger'
    default: return ''
  }
}

// 文件上传处理
const handleFileChange = (file, fileList) => {
  attachments.value = fileList.map(f => ({
    name: f.name,
    size: f.size,
    url: URL.createObjectURL(f.raw)
  }))
}

const handleFileRemove = (file, fileList) => {
  attachments.value = fileList
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true
    await formRef.value.validate()
    
    // 准备合同数据
     const contractData = {
      contractNumber: form.value.contractId, 
      title: form.value.title,
      applicant: form.value.applicant,
      companyName: form.value.partyBCompany,  
      contractType: '租赁合同',               
      startDate: form.value.contractStartDate, 
      contractStatus: '待审批',                
      companyAddress: form.value.partyBAddress, 
      endDate: form.value.contractEndDate
    }

    let response
    
    if (isEditMode.value) {
      // 编辑模式 - 调用更新接口
      const contractId = parseInt(route.query.id)
      response = await api.put(`/api/contracts/${contractId}/with-attachments`, {
        ...contractData,
        attachments: attachments.value
      })
      ElMessage.success('合同变更申请已提交')
    } else {
      // 新增模式 - 调用创建接口
      response = await api.post('/api/contracts/with-attachments', {
        ...contractData,
        attachments: attachments.value
      })
      ElMessage.success('新合同申请已提交')
    }

    // 显示成功对话框
    successDialogVisible.value = true
    
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response) {
      const errorMsg = error.response.data?.message || error.response.data || '提交失败'
      ElMessage.error(`提交失败: ${errorMsg}`)
    } else {
      ElMessage.error('请填写完整的合同信息')
    }
  } finally {
    submitting.value = false
  }
}

// 成功对话框确认
const handleSuccessConfirm = () => {
  successDialogVisible.value = false
  router.push('/contractside')
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 初始化加载数据
const loadContractData = async () => {
  if (isEditMode.value && route.query.id) {
    try {
      const contractId = parseInt(route.query.id)
      const response = await api.get(`/api/contracts/${contractId}/with-attachments`)
      
      if (response.code === 200 && response.data) {
        const contract = response.data
        form.value = {
          contractId: contract.number,
          title: contract.title,
          applicant: contract.applicant,
          contractStartDate: contract.date,
          partyBCompany: contract.name,
          partyBAddress: contract.partyBAddress || '默认乙方地址',
          contractEndDate: contract.contractEndDate,
          status: contract.status,
          changeReason: contract.changeReason || ''
        }
        
        // 加载附件
        if (contract.attachments && contract.attachments.length > 0) {
          attachments.value = contract.attachments
        }
      } else {
        ElMessage.error('未找到该合同')
        router.push('/contractside')
      }
    } catch (error) {
      console.error('加载合同数据失败:', error)
      ElMessage.error('加载合同数据失败')
      router.push('/contractside')
    }
  } else if (!isEditMode.value) {
    resetForm()
  }
}
// 初始化加载数据
onMounted(() => {
  loadContractData()
})
</script>

<style scoped>
.contract-apply-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.form-card {
  border-radius: 12px;
  padding: 30px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  color: #666;
  font-size: 16px;
}

.subtitle .required {
  color: #F56C6C;
  margin: 0 3px;
}

.contract-form {
  margin-top: 30px;
}

.upload-area {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  padding: 40px 20px;
}

.el-upload__tip {
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.success-message {
  text-align: center;
  padding: 20px;
}

.success-message h3 {
  margin: 20px 0 10px;
  font-size: 22px;
  color: #333;
}

.success-message p {
  color: #666;
  margin: 5px 0;
  font-size: 16px;
}

@media (max-width: 768px) {
  .contract-form :deep(.el-form-item__label) {
    text-align: left;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style>